<template>
	<div>
	  <div id="mapContainer" style="width: 100%; height: 100vh;">
    </div>
    <Infowindow ref="infoWindow" :form='markerInfo' />
	</div>
  </template>
  
  <script>
  import { vehicleMonitorDetail } from "@/api/vehicle/position/data"; 
  import Infowindow from './Infowindow'
  
  import Vue from "vue";
  import VueAMap  from 'vue-amap';
  Vue.use(VueAMap) // 使用插件
  VueAMap.initAMapApiLoader({ // 初始化插件
    key: 'ce62a9471fd2858f6dfe96a6f4708fca', // 高德key
    plugin: [
    "AMap.Autocomplete", //输入提示插件
    "AMap.PlaceSearch", //POI搜索插件
    "AMap.Scale", //右下角缩略图插件 比例尺
    "AMap.OverView", //地图鹰眼插件
    "AMap.ToolBar", //地图工具条
    "AMap.MapType", //类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
    "AMap.PolyEditor", //编辑 折线多，边形
    "AMap.CircleEditor", //圆形编辑器插件
    "AMap.Geolocation", //定位控件，用来获取和展示用户主机所在的经纬度位置
    "AMap.ControlBar",
    'AMap.ToolBar',
    'AMap.Driving',
    'AMap.Geocoder'       
    ], 
    uiVersion: '1.0.11', // 不加会报错，加上吧
    v: '1.4.15' // 默认高德 sdk 版本为 1.4.4
  })
//   import AmapVue from '@amap/amap-vue';

// AmapVue.config.version = '2.0'; // 默认2.0，这里可以不修改
// AmapVue.config.key = '44703c6aa86142aca11279c81aa94534';
// AmapVue.config.plugins = [
//   // 在此配置你需要预加载的插件，如果不配置，在使用到的时候会自动异步加载
// ];
// Vue.use(AmapVue);


import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";
const amapManager = new AMapManager();
export default {
  components: {Infowindow},

  props: {
        options: {
            type: Object,
            default: () => {
                return {
                    mapType: 'roadmap',
                    position: { lat: 51.5073509, lng: -0.1277583 },
                    isSearch: false, //是否显示搜索框
                    showInfo: false, //是否显示信息弹框
                    isTrack: false, //是否显示轨迹
                    height: '300px', //地图的高度
                    posList: [], //gps数组,
                    trackList: [], //轨迹数组
                    infos: {}, //信息弹框的内容
                    address: '', //地址
                    state: 0  //设备状态

                }
            }
        }
    },
    watch: {
        options: {
            handler: function (val) {
        
                this.posList = val.posList;
                if ( this.map ) {
                  if (val.mapType == 'roadmap') {
		              // 切换回普通地图
		              this.map.setLayers([new AMap.TileLayer()]);
		            } else {
		              // 切换为卫星图
		              this.map.setLayers([
		            	new AMap.TileLayer.Satellite(),
		            	new AMap.TileLayer.RoadNet() // 显示路网
		              ]);
		            }
                }
               
                if (val.isSearch) {
                    this.searchValue = val.address;
                    this.searchMarker = val.position;
                    this.showSearch = val.isSearch;
                    // this.$nextTick(() => {
                    //     this.$refs.googlemap.panTo(val.position);
                    // })
                    this.zoom = 5;
                }

                if (val.showInfo) {
                    this.isOpenInfoWin = true;
                    this.infoWinPos = val.position;
                    // this.$nextTick(() => {
                    //     this.$refs.googlemap.panTo(val.position);
                    // })
                    this.zoom = 5;
                }
                    console.log(val);
                //监听属性来创建轨迹
                if (val.isTrack && val.trackList.length) {
                    console.log(val);
                    this.$nextTick(() => {
                        //gps的数组
                        this.sectionPath = val.trackList;
                        //设置起始和结束的标记点
                        this.pointsMarker = this.setStartEndPoint(this.sectionPath);
                        this.vehicleMarkers = this.setMoveVehicle(this.sectionPath, true)
                        //创建骑行轨迹点
                        val.trackList.forEach((item)=>{
                            this.trackPoints.push([item.lng,item.lat])
                        })
                        // //绘制行程轨迹
                        // this.drawTrack();
                        // //设置轨迹起始点
                        // this.setStartEndPoint(val.trackList);
                        // this.zoom = 20;
                        setTimeout(()=>{
                    //绘制行程轨迹
                    this.drawTrack();
                        //设置轨迹起始点
                        this.setStartEndPoint(val.trackList);
                        this.zoom = 20;

                  },1000)

                    })

                }
                //监听属性来更新车辆位置标记
                if (!val.isTrack && val.posList.length) {
                    console.log("车辆标记位置列表",val.posList);
                    if (this.markers.length) {
                        this.isOpenInfoWin = false;
                        this.markers = this.setMoveVehicle(val.posList);
                        this.markers.forEach(item => {
                            item.visible = val.state ? (item.content.state === val.state ? true : false) : true
                        })

                    } else {
                        this.$nextTick(() => {
                            this.markers = this.setMoveVehicle(val.posList);
                            this.oMarkers = [...this.markers]
                        })
                    }


                }
                if (val.posList.length == 0) {
                    this.markers = [];
                }
                  setTimeout(()=>{
                    this.handleMarker();

                  },1000)
                 
              },
            immediate: true,
            deep: true,
            
        }
    },
	data() {
	  return {
		center: [116.397428, 39.90923], // 地图中心点
		zoom: 11,
		markers: [],
		markerData: [],
		map: undefined,
		markerClusterer: undefined,
		count: 0,
		isSatellite: false, // 用于跟踪当前地图类型是否为卫星图
    moveMarker:null,
    coordinates:[],
		trackPoints: [], // 轨迹的经纬度坐标点,
    markerList:[],
    icons: [require('@/assets/images/onLine.png'), require('@/assets/images/offLine.png'), require('@/assets/images/park.png')],
    markerInfo:{},
    amapMarkers:[]
	};
	},
	mounted() {
    setTimeout(()=>{
      this.initMap()
    },1000)
	},
	methods: {
	  initMap() {
		  this.map = new AMap.Map('mapContainer', {
		    center: this.center,
		    zoom: this.zoom,
		    layers: [
		  	new AMap.TileLayer() // 默认普通地图图层
		    ]
		  });
	  },
    //初始化获取车辆标记位置
	  handleMarker() {
		  AMap.plugin(['AMap.MarkerClusterer'], () => {
		    if (this.markerClusterer) {
		  	  this.markerClusterer.clearMarkers();
		    }
		    this.markerData = this.markers.map(marker => {
		  	const amapMarker = new AMap.Marker({
		  	  position: [marker.position.lng,marker.position.lat],
		  	  label: {
		  		content: marker.title,
		  		offset: new AMap.Pixel(-50, 50),
		  	  },
		  	  icon: marker.icon.url
		  	});
		  	amapMarker.on('click', () => {
		  	  this.handleMarkerClick(marker, amapMarker, this.map);
		  	});
        this.amapMarkers.push(amapMarker);
		  	return amapMarker;
		    });
		    this.markerClusterer = new AMap.MarkerClusterer(this.map, this.markerData, {
		  	gridSize: 80,
		  	minClusterSize: 2,
		  	maxZoom: 18,
		    });
        console.log(this.markerData,this.map);
		  });
	  },
    //重置所有标记点，并没有用到
	  resetMarkers() {
		  if (this.markerClusterer) {
		    this.markerClusterer.clearMarkers();
		  }
		  this.markerData.forEach(marker => {
		    marker.setMap(null);
		  });
		  this.markerData = [];
	  },
	 //点击图标移动中心点并且打开infowindow
	  handleMarkerClick(marker, amapMarker, map) {
      vehicleMonitorDetail({ deviceCode: marker.deviceCode }).then(res => { 
                    console.log("点击某个详情",this.$refs.infoWindow.$el);
               
                if (res.data.lat || res.data.lng) {
                    // this.getAddress(res.data.lat,res.data.lng)
                    this.markerInfo = res.data;
                    // this.infoWindowPosition = { lat:parseFloat(item.position.lat), lng: parseFloat(item.position.lng) };
                    this.centers = this.infoWinPos
                    this.count++;
                }
                if(this.cancel==0 &&(res.data.lat == null || res.data.lng == null)){
                    this.msgSuccess(this.$t('prompt.noGps'));
                    this.cancel++;
                }else{
                    this.cancel =0;
                }
              })
              setTimeout(()=>{
                  const infoWindow = new AMap.InfoWindow({
		                  content: this.$refs.infoWindow.$el,
		                  offset: new AMap.Pixel(10, -30),
		                });
                    console.log("position=====>",amapMarker.getPosition());
		                    infoWindow.open(map, amapMarker.getPosition());
              },1000)
	  },
	drawTrack() {
      // 清除先前的轨迹
      // this.clearTrack();
      // 创建轨迹折线
      const trackPolyline = new AMap.Polyline({
        path: this.trackPoints,
        strokeColor: '#3366FF', // 线条颜色
        strokeOpacity: 1, // 线条透明度
        strokeWeight: 5, // 线条宽度
        map: this.map
      });
      // 将地图视角移动到轨迹的起点
      // this.map.setZoomAndCenter(newZoom, amapMarker.getPosition());

      this.map.setCenter(this.trackPoints[0]);
    },
    clearTrack() {
      // 清除地图上的轨迹
      this.map.clearMap();
    },


        //设置搜索位置
        setPlace(place) {
            this.searchValue = place.formatted_address + place.name
            this.place = place;
            this.searchMarker = {
                lat: this.place.geometry.location.lat(),
                lng: this.place.geometry.location.lng(),
            }
            this.$refs.map.panTo(this.searchMarker);
            this.zoom = 5;

            const params = {
                address: this.place.formatted_address + this.place.name,
                position: this.searchMarker
            }
            this.$emit('searchAddress', params)
        },
        //设置中心点
        setCenters(list) {
            // this.boundCenter = new google.maps.LatLngBounds();
            if (list && list.length) {
                list.forEach(item => {
                    if (item.lat || item.lng) {
                        // this.boundCenter.extend(new google.maps.LatLng(parseFloat(item.lat), parseFloat(item.lng)))
                    }
                })
            }
            // this.$refs.googlemap.$mapObject.fitBounds(this.boundCenter);
            // const centerLatLng = new google.maps.LatLng(46.8182, 8.2275);
            // this.$refs.googlemap.$mapObject.setCenter(centerLatLng)  //使所有点在地图居中
            // this.$refs.googlemap.$mapObject.setZoom(4);
            // this.$refs.googlemap.$mapObject.setCenter(this.boundCenter.getCenter())  //使所有点在地图居中
        },
        //设置起始结束点标记
        setStartEndPoint(list) {
            let points = [];
            //起始点
            let sPoint = {
                position: {
                    lng: parseFloat(list[0].lng),
                    lat: parseFloat(list[0].lat)
                },
                icon: {
                    url: require('@/assets/images/startNew.png'),
                    size: { width: 30, height: 40 }
                },
                name: 'start' + list[0].direction
            }
            //结束点
            let ePoint = {
                position: {
                    lng: parseFloat(list[list.length - 1].lng),
                    lat: parseFloat(list[list.length - 1].lat)
                },
                icon: {
                    url: require('@/assets/images/endNew.png'),
                    size: { width: 30, height: 40 }
                },
                name: 'end' + list[0].direction
            }
            points.push(sPoint, ePoint);
           
            points.forEach(marker => {
		        	 new AMap.Marker({
		  	      position: [marker.position.lng,marker.position.lat],
		  	      icon: marker.icon.url,
              map:this.map
		        	})
            })
        },
        //设置车辆位置标记, isMove:表示移动车辆
        setMoveVehicle(list, isMove = false) {
            let vehicleMakers = []

            list.forEach(item => {

                if (item.lat || item.lng) {
                    const url = item.state === 1 ? this.icons[1] : item.state === 2 ? this.icons[0] : this.icons[2];
                    let vMarker = {
                        deviceCode: !isMove ? item.deviceCode : undefined,
                        title: !isMove ? item.vehicleType : undefined,
                        position: {
                            lat: item.lat,
                            lng: item.lng
                        },
                        icon: {
                            url: isMove ? this.icons[0] : url,
                            size: {
                                width: 39,
                                height: 55
                            },
                            labelOrigin: { x: 20, y: 70 },
                            // scaledSize: new google.maps.Size(39, 55)
                        },
                        name: 'vehicle' + item.direction,
                        content: isMove ? '' : item,
                        visible: true,
                        label: isMove ? '' : { color: '#ffffff', className: 'map_label', text: item.vehicleType }
                    }
                    vehicleMakers.push(vMarker);
                }
            })
            return vehicleMakers;
        },
        //车辆移动
        handleVehicleMove(index, flag,) {
              // 创建移动车辆图标对象
            if (this.moveMarker != null) {
               // 更新图标位置为下一个路线点
               this.moveMarker.setPosition(this.trackPoints[index]);
              //移动地图中心点
              this.map.setCenter(this.trackPoints[index])

            }else{
              this.moveMarker = new AMap.Marker({
                position: this.trackPoints[0], // 初始位置为轨迹起点
                icon: this.icons[0], // 图标的 URL
                offset: new AMap.Pixel(-15, -45), // 图标偏移量
                map: this.map // 图标所在的地图对象
              });
            }
                           
        },
        //根据多选框移动到标记点并且打开弹窗
        openInfoWindowClickOneMore(item) {
          console.log(item);
             vehicleMonitorDetail({ deviceCode: item.deviceCode }).then((res) => {
               //   如果获取到的位置信息为空（即没有获取到经纬度），则给用户提示，表示没有获取到 GPS 信号。
              if (res.data.lat == null || res.data.lng == null || res.data.lat == 0 || res.data.lng == 0) {
                this.$modal.msgError(this.$t("vehicle.position.noGps"));
              }   
              var amapMarker ;
                this.amapMarkers.forEach((x)=>{
                    if (x.w.label.content == item.deviceCode) {
                      amapMarker = x;
                    }
                })
                this.markerInfo = res.data;
                    const newZoom = 25; // 您可以根据需要设置新的缩放级别
                    // 将地图视角移动到指定位置并增大范围
                    this.map.setZoomAndCenter(newZoom, amapMarker.getPosition());
                    setTimeout(()=>{
                      const infoWindow = new AMap.InfoWindow({
		                      content: this.$refs.infoWindow.$el,
		                      offset: new AMap.Pixel(10, -30),
		                    });
		                        infoWindow.open(this.map, amapMarker.getPosition());
                    },1000)
             })
        }
	},
  };
  </script>
  
  <style>

  .amap-marker-label {
	background-color: black; /* 设置标签背景颜色 */
	border: 1px solid black; /* 设置标签边框 */
	padding: 5px; /* 设置标签内边距 */
	border-radius: 5px; /* 设置标签圆角 */
	color: white; /* 设置标签文字颜色 */
	font-size: 14px; /* 设置标签文字大小 */
	width: 130px; /* 设置标签宽度 */
	height: 30px; /* 设置标签高度 */
	line-height: 20px; /* 设置标签行高，使文本垂直居中 */
	text-align: center; /* 设置文本居中 */
  }
  </style>
  